#!/usr/bin/env python3
"""
protobuf-c MCP Server

面向 protobuf-c 软件的 MCP server，提供 Protocol Buffers C 语言版本的编译功能。

MCP tools 列表：
1. protobuf_c_compile_proto
   - 用途：编译 .proto 文件生成 C 语言代码
   - 参数：proto_file (str): .proto 文件路径, output_dir (str): 输出目录
   - 返回：统一的 JSON 结构，包含执行结果
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import os
from typing import Dict, Any

mcp = FastMCP("protobuf-c MCP Server")

@mcp.tool()
def protobuf_c_compile_proto(proto_file: str, output_dir: str = "./") -> Dict[str, Any]:
    """
    使用 protoc-c 编译 .proto 文件生成 C 语言代码
    
    参数:
        proto_file: .proto 文件的路径
        output_dir: 输出目录，默认为当前目录
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 是否执行成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    # 检查 proto 文件是否存在
    if not os.path.exists(proto_file):
        return {
            "success": False,
            "command": f"protoc-c --c_out={output_dir} {proto_file}",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Error: Proto file '{proto_file}' does not exist"
        }
    
    # 执行 protoc-c 编译命令
    command = ["protoc-c", f"--c_out={output_dir}", proto_file]
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()